//
//  RHMEDevMasterVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/2/28.
//

#import "RHMEDevMasterVC.h"
#import "RHDeviceBatteryCell.h"
#import "RHBlockDetailVC.h"
#import "RHBlockPCSParaVC.h"
#import "RHBlockBatteryClusterVC.h"
#import "RHDevEndPointDataModel.h"
#import "RHDevDataModel.h"
#import "SYChartTool.h"
#import "RHCommonDataCell.h"

@interface RHMEDevMasterVC ()<UITableViewDelegate,UITableViewDataSource>


@property (nonatomic ,strong) UITableView *tableView;

@end

@implementation RHMEDevMasterVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    [self setupUI];
    [self getAllData];
    
}

-(NSArray*)createMasterData
{
    NSArray *arr = [SYChartTool loadJsonFileWithName:@"Dev_master"];
    return [NSArray yy_modelArrayWithClass:[RHDevDataModel class] json:arr];
}

-(void)setupUI
{
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    _tableView.estimatedRowHeight = 150;
    _tableView.rowHeight = UITableViewAutomaticDimension;
    [_tableView registerClass:[RHCommonDataCell class] forCellReuseIdentifier:CommonNormalCell];
    [_tableView registerClass:[RHCommonDataCell class] forCellReuseIdentifier:CommonStatusCell];
    [_tableView registerClass:[RHCommonDataCell class] forCellReuseIdentifier:CommonIndicatorCell];
    [_tableView registerClass:[RHCommonDataCell class] forCellReuseIdentifier:CommonProgressCell];
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(10, 0, 0, 0));
    }];
    
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
    
    kWeakSelf;
    [_tableView addHeaderRefresh:^{
        [weakSelf getAllData];
    }];
}
#pragma mark ---------------- network -----------
//获取端点关系
- (void)getAllData{
  
        [self.masterSectionArr enumerateObjectsUsingBlock:^(RHDevEndPointDataModel  *_Nonnull emsModel, NSUInteger idx, BOOL * _Nonnull stop) {
            emsModel.infoArr = [self createMasterData];
            [self getDataWithGroupIndex:idx];
        }];
        
}

//-(void)getDeviceMasterList
//{
//    [QMUITips showLoadingInView:self.view];
//    NSDictionary *para = @{@"deviceId":self.deviceModel.deviceId,
//                           @"endpointTypeCode":@[@"Master"],
//                           @"group":@(1)};
//    [RHDevMasterModel startWithCompletionAPIKey:H_getEndpointByType argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
//        if(resultModel.code == 200){
//            if([request.responseJSONObject[@"data"] isKindOfClass:[NSArray class]]){
//                NSArray *dataArr = request.responseJSONObject[@"data"];
//                NSMutableArray *tempArr = [NSMutableArray array];
//                [dataArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//                    if([obj isKindOfClass:[NSDictionary class]]){
//
//                        NSDictionary *dic = obj;
//                        if([dic[@"endpointList"] isKindOfClass:[NSArray class]]){
//                            NSArray *listArr = dic[@"endpointList"];
//                            NSArray *masterArr = [NSArray yy_modelArrayWithClass:[RHDevMasterModel class] json:listArr];
//                            [tempArr addObject:masterArr];
//                        }
//                    }
//                }];
//
//                //这里的数据是已经分组,取对应EMS的那组信息
//                if(self.index < tempArr.count){
//                    self.masterSectionArr = tempArr[self.index];
//                    kWeakSelf;
//                    [self.masterSectionArr enumerateObjectsUsingBlock:^(RHDevMasterModel  *_Nonnull masterModel, NSUInteger idx, BOOL * _Nonnull stop) {
//                        masterModel.infoArr = [self createMasterData];
//                        [weakSelf getDataWithGroupIndex:idx];
//                    }];
//                }
//
//            }
//
//            [self.tableView reloadData];
//
//        }
//        [self.tableView endHeaderRefresh];
//    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
//        [self.tableView endHeaderRefresh];
//    }];
//}

//获取每个master下的数据点
-(void)getDataWithGroupIndex:(NSInteger)index
{
    RHDevEndPointDataModel *masterModel = self.masterSectionArr[index];
    [QMUITips showLoadingInView:self.view];
    NSMutableArray *keyCodes = [NSMutableArray array];
    [masterModel.infoArr enumerateObjectsUsingBlock:^(RHDevDataModel  *_Nonnull dataModel, NSUInteger idx, BOOL * _Nonnull stop) {
        [keyCodes addObject:dataModel.keyCode];
    }];
    //json文件里用了Mtr_cur
    [keyCodes addObject:@"Mtr_TV"];
    NSDictionary *para = @{@"deviceId":self.deviceModel.deviceId,
                           @"endpointTypeCode":masterModel.type,
                           @"keyCodes":keyCodes,
                           @"endpointSn":masterModel.sn
    };
    [BaseModel startWithCompletionAPIKey:D_getLastEndpointData argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200){
            if([request.responseObject[@"data"] isKindOfClass:[NSDictionary class]]){
                NSDictionary *dic = request.responseObject[@"data"];
                masterModel.data = dic;
                RHDevDataModel *pw_model = masterModel.infoArr[1];
                double power = [ValidNullData(dic[@"Mtr_Cur"]) floatValue] *  [ValidNullData(dic[@"Mtr_TV"]) floatValue];
                NSNumber *n_value = [NSNumber numberWithDouble:power];
                pw_model.content = [n_value twoDecimalPlacesWithoutRounding];
                [self.tableView reloadData];
            }
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
    
}

#pragma mark - UITableViewDelegate,UITableViewDataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.masterSectionArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    RHDevEndPointDataModel *masterModel = self.masterSectionArr[section];
    return masterModel.infoArr.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 35;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 60;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 60)];
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, 10, kUI_WINDOW_W-30, 50)];
    [headView addSubview:bgView];
    bgView.layer.cornerRadius = 8;
    bgView.layer.masksToBounds = YES;
    bgView.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner;
    bgView.backgroundColor = [UIColor whiteColor];
    UIImageView *icon = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"block_icon"]];
    [bgView addSubview:icon];
    
    UIImageView *arrowIcon = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"arrow_2"]];
    [bgView addSubview:arrowIcon];
    
    UILabel *titleLab = [[QMUILabel alloc]init];
    titleLab.font = kBOLDSYSTEMFONT(14);
    titleLab.textColor = kColorRGB(0, 0, 0);
    titleLab.textAlignment = NSTextAlignmentLeft;
    titleLab.text = [NSString stringWithFormat:@"%ld#%@",section+1,@"能量体".rh_localized];
    [bgView addSubview:titleLab];
    
    
    QMUIButton *detailBtn = [[QMUIButton alloc]init];
    [bgView addSubview:detailBtn];
    
    UIView *line = kView;
    line.backgroundColor = kCOLOR_HEX(@"EBEDF0");
    [bgView addSubview:line];
    
    [icon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(@(CGSizeMake(20, 20)));
        make.left.mas_offset(15);
        make.centerY.mas_offset(0);
    }];
    
    [arrowIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-15);
        make.size.equalTo(@(CGSizeMake(18, 18)));
        make.centerY.mas_offset(0);
    }];
    
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(icon.mas_right).offset(15);
        make.centerY.equalTo(icon);
     }];
    
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.offset(1);
        make.bottom.mas_offset(-5);
    }];
    
    [detailBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    kWeakSelf;
    [[detailBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        RHBlockDetailVC *vc = [[RHBlockDetailVC alloc]init];
        vc.devModel = weakSelf.deviceModel;
        RHDevEndPointDataModel *model = weakSelf.masterSectionArr[section];
        vc.curEmsModel = weakSelf.curEmsModel;
        vc.curMaterModel = model;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    
   return headView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 60 +20;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footer = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 60 + 25)];
    footer.backgroundColor = CFTabViewBgColor;
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, 0, footer.width-30, 45 +25)];
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.layer.cornerRadius = 8;
    bgView.layer.masksToBounds = YES;
    bgView.layer.maskedCorners = kCALayerMinXMaxYCorner|kCALayerMaxXMaxYCorner;
    
    UIView *line2 = kView;
    line2.backgroundColor = kCOLOR_HEX(@"E7E7E7");
    [bgView addSubview:line2];
    
    UIView *line3 = kView;
    line3.backgroundColor = kCOLOR_HEX(@"E7E7E7");
    [bgView addSubview:line3];
    
    line2.hidden = YES;
    line3.hidden = YES;
    
    QMUIButton *pcsBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [pcsBtn setTitle:@"PCS" forState:UIControlStateNormal];
    [pcsBtn setTitleColor:kCOLOR_HEX(@"3F4443") forState:UIControlStateNormal];
    pcsBtn.titleLabel.font = kSYSTEMFONT(14);
    [pcsBtn setBackgroundColor:kCOLOR_HEX_A(@"#405DBE", 0.08)];
    [pcsBtn setCornerRadius:8];
    [bgView addSubview:pcsBtn];
    
    kWeakSelf;
    //PCS运行参数
    [[pcsBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        RHBlockPCSParaVC *pcsVC = [[RHBlockPCSParaVC alloc]init];
        pcsVC.deviceModel = weakSelf.deviceModel;
        pcsVC.curEMSModel = weakSelf.curEmsModel;
        pcsVC.curMasterModel = weakSelf.masterSectionArr[section];
        [weakSelf.navigationController pushViewController:pcsVC animated:YES];
    }];
    
    QMUIButton *clusterBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [clusterBtn setTitle:@"电池族".rh_localized forState:UIControlStateNormal];
    [clusterBtn setTitleColor:kCOLOR_HEX(@"3F4443") forState:UIControlStateNormal];
    clusterBtn.titleLabel.font = kSYSTEMFONT(14);
    [clusterBtn setBackgroundColor:kCOLOR_HEX_A(@"#405DBE", 0.08)];
    [clusterBtn setCornerRadius:8];
    [bgView addSubview:clusterBtn];
    
    //电池簇
    [[clusterBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        RHBlockBatteryClusterVC *clusterVC = [[RHBlockBatteryClusterVC alloc]init];
        clusterVC.title = [NSString stringWithFormat:@"%ld#%@",section+1,@"电池簇".rh_localized];
        clusterVC.devModel = weakSelf.deviceModel;
        RHDevEndPointDataModel *masterModel = weakSelf.masterSectionArr[section];
        clusterVC.masterSN = masterModel.sn;
        [weakSelf.navigationController pushViewController:clusterVC animated:YES];
    }];

    
    [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.mas_offset(0);
        make.height.offset(1);
    }];
    
    [pcsBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.top.equalTo(line2.mas_bottom).offset(10);
        make.right.equalTo(line3.mas_left).offset(-15);
        make.height.offset(45);
    }];
    
    [clusterBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(line3.mas_right).offset(15);
        make.top.equalTo(pcsBtn);
        make.size.equalTo(pcsBtn);
        make.bottom.mas_offset(-15);
    }];
    
    [line3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(line2.mas_bottom);
        make.centerX.mas_offset(0);
        make.width.offset(1);
        make.bottom.equalTo(pcsBtn);
    }];
    

    
    [footer addSubview:bgView];
    return footer;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    RHCommonDataCell *cell;
    RHDevEndPointDataModel *masterSectionModel = self.masterSectionArr[indexPath.section];
    RHDevDataModel *dataModel = masterSectionModel.infoArr[indexPath.row];
    NSInteger celltype = dataModel.type ;
    if(celltype == CommonCellTypeNormal){
        cell = [tableView dequeueReusableCellWithIdentifier:CommonNormalCell];
    }else if (celltype == CommonCellTypeStatus){
        cell = [tableView dequeueReusableCellWithIdentifier:CommonStatusCell];
    }else if (celltype == CommonCellTypeIndicator){
        cell = [tableView dequeueReusableCellWithIdentifier:CommonIndicatorCell];
    }else if (celltype == CommonCellTypeProgress){
        cell = [tableView dequeueReusableCellWithIdentifier:CommonProgressCell];
    }
    cell.dataModel = dataModel;
    return cell;
}

@end
